<template>
    <div class="addProject business-workAdd">
        <div class="addForm zll-form">
			<el-form :model="addForm" :rules="rules" ref="addForm" class="demo-ruleForm">
				<el-row :gutter="40">
					<el-col :span="8">
						<el-form-item class="formList" prop="name" label="创建人：">
							<el-input clearable class="input_right"  v-model="createrName" :disabled=true ></el-input>
						</el-form-item>
                    </el-col>
					<el-col :span="8" v-if="type!=='add'">
						<el-form-item class="formList" prop="type" label="编辑人：">
							<el-input clearable class="input_right"  v-model="addForm.editorName" :disabled=true ></el-input>
						</el-form-item>
                    </el-col>
                </el-row>
                <div class="con_p">
                    <div class="mine-add" v-if="type == 'add'">
                        <span class="tipss">单次添加最多5个产品</span>
                        <span @click="addTable()"><i class="el-icon-circle-plus"></i></span>
<!--                        <span @click.stop="deleteTable(tableList,'')"><i class="el-icon-remove-outline"></i></span>-->
                    </div>
                </div>
                <div class="tableList">
                    <table border="1">
                        <tr>													
                            <th width="40"></th>
                            <th>大类</th>
                            <th>品类</th>
                            <th>物料代码</th>
                            <th>物料名称</th>
                            <th width="200">规格</th>
                            <th>计量单位</th>
                            <th>状态</th>
                            <th width="60"></th>
                        </tr>
                        <tr v-if="addForm.tableList.length == 0" class="noData"><td colspan="9">暂无数据</td></tr>
                        <tr v-else class="add_Table" v-for="(item, index) in addForm.tableList"  :key="index">
                            <td width="40">
								{{index + 1}}
<!--                                <el-checkbox v-model="item.checked"  v-if="type == 'add'"></el-checkbox>-->
                            </td>
                            <td>
                                <el-select v-model="item.itemName" placeholder="大类" @change="itemNameChange(item)" class="text_center" clearable :disabled="type == 'see'">
									<el-option v-for="(itemName,itemNameIndex) in item.itemNameList" :key="itemNameIndex" :label="itemName" :value="itemName"></el-option>
                                </el-select>
                            </td>
                            <td>
                                <el-select v-model="item.itemAlias" placeholder="品类" class="text_center" clearable :disabled="type == 'see'">
									<el-option v-for="(itemAlias,itemAliasIndex) in item.itemAliasList" :key="itemAliasIndex" :label="itemAlias.itemAlias" :value="itemAlias.id"></el-option>
                                </el-select>
                            </td>
                            <td><el-input v-model="item.materialCode" placeholder="物料代码" class="text_center" clearable :disabled="type == 'see'"></el-input></td>
                            <td><el-input v-model="item.materialName" placeholder="物料名称" class="text_center" clearable :disabled="type == 'see'"></el-input></td>
                            <td width="200"><el-input v-model="item.formatMaterial" placeholder="" class="text_center" clearable :disabled="type == 'see'"></el-input></td>
                            <td>
                                <el-select v-model="item.measureUnitId" placeholder="规格" class="text_center" clearable :disabled="type == 'see'">
									<el-option v-for="(measureUnit,unitIndex) in measureUnitList" :key="unitIndex" :label="measureUnit.itemName" :value="measureUnit.id"></el-option>
                                </el-select>
                            </td>
                            <td>
                                <el-select v-model="item.materialStatus" placeholder="状态" class="text_center" clearable :disabled="type == 'see'">
                                    <el-option label="停用" value="1"></el-option>
                                    <el-option label="启用" value="0"></el-option>
                                </el-select>
                            </td>
                            <td width="60">
                                <span class="edit" @click.stop="deleteTable(item,index)"  v-if="type == 'add'">删除</span>
                            </td>
                        </tr>
                    </table>
                </div>
            </el-form>
        </div>


    </div>
</template>
<script>
import {getStore} from "../../../../plugins/localStore";
import {formatDate} from "../../../../plugins/formatDate";

export default {
    props: ['type','editData','itemNameList','itemMap'],
    data(){
        return {
            addForm: {
				tableList: [{
				}]
            },
			measureUnitList: [],
			createrName : getStore().userName+" "+formatDate(new Date(), 'yyyy-MM-dd'),

			count: 0,

            rules: {
               
            }
        }
    },
    methods: {
		getUnitList(){
			let self = this;
			let param = {itemName:'',status:'',itemType:'3'};
			self.$http({
				url: "/jinl/sysItem/getMgItemList",
				method: "post",
				params:param
			}).then(resp => {
				if (resp.success) {
					self.measureUnitList = resp.result;
				}

			});

		},

		itemNameChange(item){
			debugger
			item.categoryId = '';
			item.itemAliasList = item.itemMap[item.itemName];
			// 清空品类下拉框的值
			item.itemAlias = '';
		},

        addTable() {
            if(this.addForm.tableList.length < 5) {
                this.addForm.tableList.push(
                    {
						itemName: '',
						itemAlias: '',
						materialCode: '',
						materialName: '',
						formatMaterial: '',
						measureUnit: '',
						materialStatus: '',
						id: '',
						itemAliasList:[],
						itemNameList:JSON.parse(JSON.stringify(this.itemNameList || [])),
						measureUnitList:JSON.parse(JSON.stringify(this.measureUnitList || [])),
						itemMap: JSON.parse(JSON.stringify(this.itemMap || {})),
					},
                );
            }else {
                this.$notify({ title: '提示', message: "单次添加最多5条", type: 'warning' });
            }
        },
        deleteTable(item,index) {//删除table
            let self = this;
            if( index !== '' ) {
                self.addForm.tableList.splice(index,1)
            }else {
                let checkTable = item;
                for(let i = 0; i < checkTable.length; i++) {
                    checkTable = checkTable.filter((val) => {
                        return !val.checked
                    })
                }
                self.addForm.tableList = checkTable
            }
        },
		submitForm() {
			debugger
			console.log("wwwzz")
			let self = this;
            for (let data of self.addForm.tableList) {
				data.categoryId = data.itemAlias;
				console.log(data)
                if (!data.itemName) {
                    self.$message.warning('请选择大类');
                    return -1;
                } else if (!data.categoryId) {
                    self.$message.warning('请选择品类');
                    return -1;
                } else if (!data.materialCode) {
                    self.$message.warning('请输入物料代码');
                    return -1;
                } else if (!data.materialName) {
                    self.$message.warning('请输入物料名称');
                    return -1;
                // } else if (!data.formatMaterial) {
                //     self.$message.warning('请输入规格');
                //     return -1;
                } else if (!data.measureUnitId) {
                    self.$message.warning('请选择计量单位');
                    return -1;
                } else if (!data.materialStatus) {
                    self.$message.warning('请选择状态');
                    return -1;
                } 
            }

			self.operate();
		},

		operate() {
			if(this.type == 'add'){
				this.addMaterial();
			}else if(this.type == 'edit'){
				this.updateMaterial();
			}
		},

		addMaterial(){
			let self = this;
			if (self.addForm.tableList.length == 0){
				self.$message.warning('至少添加一条记录！');
				return;
			}

			let user = getStore();
			let params = [];
			let index = 1;
			let materialCodeRepeats = [];

			for (let data of self.addForm.tableList){
				if (materialCodeRepeats.includes(data.materialCode)){
					self.$message.warning('第'+index+'条记录物料代码已存在!');
					return;
				}
				materialCodeRepeats.push(data.materialCode);
				++index;

				let param = {
					categoryId: data.categoryId,
					materialCode: data.materialCode,
					materialName: data.materialName,
					formatMaterial: data.formatMaterial,
					measureUnitId: data.measureUnitId,
					materialStatus: data.materialStatus,
					createrId: user.id,
					editorId: user.id

				};
				params.push(param);
			}

			if (this.count == 0){
				self.count++;
				self.$http({
					url: "/jinl/material/addMaterial",
					method: "post",
					data: JSON.stringify(params),
					dataType: 'json',
					contentType: 'application/json',
				}).then(resp=>{
					if (resp.success) {
						self.$message.success('操作成功');
						self.$emit('refreshData');
						return

					}
					self.$message.error(resp.message);
					self.count--;
				})
			}
		},

		updateMaterial(){
			debugger
			let self = this;
			if(self.addForm.tableList.length == 0){
				self.$message.warning('至少添加一条记录！');
				return;
			}
			let user = getStore();
			let param="";
				if (self.findCategoryIdByAlias(self.addForm.tableList[0].itemAlias)=== null){
					 param = {
						 id: self.addForm.tableList[0].id,
						 categoryId: self.addForm.tableList[0].categoryId,
						 materialCode: self.addForm.tableList[0].materialCode,
						 materialName: self.addForm.tableList[0].materialName,
						 formatMaterial: self.addForm.tableList[0].formatMaterial,
						 measureUnitId: self.addForm.tableList[0].measureUnitId,
						 materialStatus: self.addForm.tableList[0].materialStatus,
						 editorId: user.id
					}
				}else {
					param = {
						id: self.addForm.tableList[0].id,
						categoryId: self.findCategoryIdByAlias(self.addForm.tableList[0].itemAlias), // 根据品类值找到对应的id
						materialCode: self.addForm.tableList[0].materialCode,
						materialName: self.addForm.tableList[0].materialName,
						formatMaterial: self.addForm.tableList[0].formatMaterial,
						measureUnitId: self.addForm.tableList[0].measureUnitId,
						materialStatus: self.addForm.tableList[0].materialStatus,
						editorId: user.id
					}
				}


			if (this.count == 0){
				self.count++;
				self.$http({
					url: "/jinl/material/updateMaterial",
					method: "post",
					data: JSON.stringify(param),
					dataType: 'json',
					contentType: 'application/json',
				}).then(resp=>{
					if (resp.success) {
						self.$message.success('操作成功');
						self.$emit('refreshData');
						return

					}
					self.$message.error(resp.message);
					self.count--;
				})
			}

		},

// 添加一个方法，根据品类值找到对应的id
		findCategoryIdByAlias(aliasValue) {
			let itemAliasList = this.addForm.tableList[0].itemAliasList;
			for (let alias of itemAliasList) {
				if (alias.itemAlias === aliasValue) {
					return alias.id;
				}
			}
			return null;
		},
    },

	watch: {
    	editData(val) {

			this.addForm.tableList=[];


    		if (this.type == 'add') {

    			this.addForm.tableList.push(
					{
						createrName: getStore().userName,
						itemName: '',
						itemAlias: '',
						materialCode: '',
						materialName: '',
						formatMaterial: '',
						measureUnit: '',
						materialStatus: '',
						id: '',
						itemNameList:JSON.parse(JSON.stringify(this.itemNameList || [])),
						measureUnitList:JSON.parse(JSON.stringify(this.measureUnitList || [])),
						itemMap: JSON.parse(JSON.stringify(this.itemMap || {})),
						itemAliasList:[],
						categoryId: val.categoryId,
					}
				);

			} else{
				let data = Object.assign({},val);
				debugger
				console.log(data)
				let itemName = data.itemName;
				this.createrName = data.createrName;
				this.addForm.editorName = data.editorName;
				this.itemAliasList = this.itemMap[itemName];
				data.itemMap = JSON.parse(JSON.stringify(this.itemMap || {})),
				data.itemNameList = JSON.parse(JSON.stringify(this.itemNameList || []));
				data.itemAliasList = data.itemMap[data.itemName];
				data.categoryId = val.categoryId;
				this.addForm.tableList.push(data);

			}

		}
	},


    mounted(){
		this.getUnitList();//显示计量单位下拉框
    },
    components: {
    }
}
</script>
<style lang="scss" scoped>
    @import "@/style/dialog.scss";
    .business-workAdd.addProject {
        .tableList {
            margin-top: 0;
            table {
                table-layout: auto;
                tr {
                    background: #fff !important;
                    td {
                        padding: 1px 3px;
                    }
                    &.noData {
                        color: #999;height: 40px;
                    }
                }
                .edit {
                    color: #1890ff;
                    padding: 0 5px;
                    cursor: pointer;
                    &.icons {
                        font-size: 16px;
                    }
                    &:hover {
                        opacity: .7;
                    }
                }
            }
        }
    }
</style>